package com.ljf.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * 说明：重写bean
 *
 * 使用BeanDefinitionRegistryPostProcessor
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/26
 */
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        logger.info("bean 定义查看和修改...");

        String beanName = "basicErrorController";

        // 先移除原来的bean定义
        beanDefinitionRegistry.removeBeanDefinition(beanName);
        String[] beanDefinitionNames = beanDefinitionRegistry.getBeanDefinitionNames();

        // 注册我们自己的bean定义
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(LjfErrorController.class);
        // 如果有构造函数参数, 有几个构造函数的参数就设置几个  没有就不用设置
//        beanDefinitionBuilder.addConstructorArgValue("构造参数1");
//        beanDefinitionBuilder.addConstructorArgValue("构造参数2");
//        beanDefinitionBuilder.addConstructorArgValue("构造参数3");
        // 设置 init方法 没有就不用设置
//        beanDefinitionBuilder.setInitMethodName("init");
        // 设置 destory方法 没有就不用设置
//        beanDefinitionBuilder.setDestroyMethodName("destory");
        // 将Bean 的定义注册到Spring环境
        beanDefinitionRegistry.registerBeanDefinition("basicErrorController", beanDefinitionBuilder.getBeanDefinition());

//        String beanName2 = "sqlSessionFactory";
//        BeanDefinition beanDefinition = beanDefinitionRegistry.getBeanDefinition(beanName2);

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        // bean的名字为key, bean的实例为value
        // 下面获取RestController.class的bean会让RestController标记的类先被注入，导致service层没有注入为null
//        Map<String, Object> beanMap = configurableListableBeanFactory.getBeansWithAnnotation(RestController.class);
//        logger.info("所有 RestController 的bean {}", beanMap);

    }


}
